package org.bdware.doip.core.codec.packet;

import io.netty.channel.ChannelHandlerContext;
import org.bdware.doip.core.doipMessage.MessageEnvelope;
import org.bdware.doip.core.exception.EnvelopeResendException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.TreeSet;

public class NoResendEnvelopeReceiveBuffer extends AbstractEnvelopeReceiveBuffer {

    HashMap<Integer,MessageEnvelope> envMap;
    int totalNumber;
    TreeSet<Integer> sortedPacketNumberSet;

    public NoResendEnvelopeReceiveBuffer(int requestId, ChannelHandlerContext ctx) {
        super(requestId);
        sortedPacketNumberSet = new TreeSet<>();
        envMap = new HashMap<>();
    }

    @Override
    public boolean isCompleted() {
        return totalNumber <= envMap.size();
    }

    @Override
    public int addEnvelope(MessageEnvelope envelope) throws EnvelopeResendException {
        if(totalNumber == 0 ) totalNumber = envelope.totalNumber;
        envMap.put(envelope.sequenceNumber,envelope);
        sortedPacketNumberSet.add(envelope.sequenceNumber);
        return totalNumber - envelope.sequenceNumber -1;
    }

    @Override
    public ArrayList<MessageEnvelope> getSortedEnvelopes() {
        //升序排列Envelope
        ArrayList<MessageEnvelope> envelopes = new ArrayList<>();
        for(int key:sortedPacketNumberSet){
            envelopes.add(envMap.get(key));
        }
        return envelopes;
    }
}
